#-*-coding:utf-8-*-
# 时间:2019/8/29
# 作者:zfh
import readConfig
from Log import MyLog
from requests_toolbelt import MultipartEncoder
import requests
import re
localReadConfig = readConfig.ReadConfig()
log = MyLog.get_log()
logger = log.logger

def md5(phone):
    # md5加密
    import hashlib
    m = hashlib.md5()
    m.update(phone.encode(encoding='utf-8'))
    return m.hexdigest()


class GetCookies:
    def __init__(self):
        # 获取token
        global cookies, initial_url
        cookies = localReadConfig.get_cookies('token')
        initial_url = localReadConfig.get_http('baseUrl')
        self.log = MyLog.get_log()
        self.logger = self.log.logger

    def send_code(self):
        '''
        发送验证码
        :return:
        '''
        # 发送短信验证的接口
        phoneNo = localReadConfig.get_cookies('phoneNo')
        api = '/api/ShortMessage/SendPassword/pic'
        # 发送短信验证接口的参数
        # MultipartEncoder函数，可以发送form-data数据，使用parm或者data请求的话，会导致错误
        m = MultipartEncoder(
            fields={'PhoneNo': phoneNo, 'skey': md5('PhoneNo=%s&dashalongV5'%phoneNo)})
        # params = {"PhoneNo":(None,"18689487780",'multipart/form-data'),"skey":(None,"2bbd67ba45dff851b34c9e6ed42d1625",'multipart/form-data')}
        # 头信息
        headers = {"content-type": "application/json;charset=UTF-8"}
        try:
            # 获取发送结果
            code_text = requests.post(initial_url + api, data=m, headers={'Content-Type': m.content_type})
            # print(code_text.text)
            print(code_text.request.body)
            # 使用正则表达式匹配到验证码
            rule = re.compile('"VerCode":"(.+?)"')
            res = rule.findall(code_text.text)
            self.logger.info("获取验证码成功")
            self.logger.info('获取验证码接口：----------耗时：%.4f' % code_text.elapsed.total_seconds())
            return res[0]
        except:
            self.logger.error("获取验证码失败")
            return False

    def login_and_get_token(self, pwd):
        '''
        登录并获取token
        :return:
        '''
        # 获取token接口
        if pwd == False:
            return False
        api = '/token'
        # 接口参数
        header = {"grant_type": "1", "username": "18576444110", "password": '%s' % pwd}
        # # 头信息
        # headers = {"content-type": "application/json;charset=UTF-8"}
        try:
            # 获取发送结果
            token_text = requests.post(initial_url + api, params=header)
            # 使用正则表达式匹配到token
            rule = re.compile('"access_token":"(.+?)"')
            res = rule.findall(token_text.text)
            self.logger.info("获取token成功")
            self.logger.info('获取token接口：----------耗时：%.4f' % token_text.elapsed.total_seconds())  # 返回结果
            localReadConfig.set_cookies('token',res[0])
            return res[0]
        except:
            self.logger.error("获取token失败")
            return False

    def drugetoken(self, token):
        '''
        通过一个测试接口，判断token是否有效存在
        如果存在，则继续使用，不存在，则在主函数调用发送短信和登录接口，获取token并写入到配置文件中
        :param token:
        :return:
        '''
        api = '/api/Course/GetFreeCourses'
        # 接口参数
        params = {"pageIndex": 1, "pageSize": 10}
        # 头信息
        headers = {"Authorization": "%s" % token}
        try:
            # 获取发送结果
            token_text = requests.post(initial_url + api, params=params, headers=headers)
            # 使用正则表达式匹配到count
            rule = re.compile(r'"result":(.+?),')
            res = rule.findall(token_text.text)
            # print(token_text.text)
            # 返回结果
            if res[0] == 'true':
                return True
            else:
                return False
        except:
            return False


# 判断token是否有效
flag = GetCookies()
if not flag.drugetoken(localReadConfig.get_cookies('token')):
    # 写入配置文件
    pwd = flag.send_code()
    token = flag.login_and_get_token(pwd)
    logger.info("<<<<<<<<<<<获取token并写入配置文件")
else:
    logger.info("<<<<<<<<<<<token有效")